package org.dolphin.service.base;

import java.io.Serializable;
import java.util.Date;
import org.dolphin.dao.UserDao;
import org.dolphin.entity.interceptor.Creatable;
import org.dolphin.entity.interceptor.Updateable;
import org.dolphin.entity.security.User;
import org.dolphin.util.DateHelper;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

public class AuditLogInterceptor extends EmptyInterceptor {
  private static final long serialVersionUID = 1090151735845844153L;
  @Autowired(required = true)
  private UserDao userDao;

  @Override
  public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
    super.onCollectionUpdate(collection, key);
  }

  @Override
  public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,
      Object[] previousState, String[] propertyNames, Type[] types) {
    if (entity instanceof Updateable) {
      Updateable log = (Updateable) entity;
      User user = userDao.getActiveUser();
      Date now = DateHelper.getCurrentDateTime();
      log.setUpdatedBy(user);
      log.setUpdatedDate(now);
      for (int i = 0; i < propertyNames.length; i++) {
        if (ObjectUtils.nullSafeEquals("updatedBy", propertyNames[i])) {
          currentState[i] = user;
        } else if (ObjectUtils.nullSafeEquals("updatedDate", propertyNames[i])) {
          currentState[i] = now;
        }
      }
      return true;
    }
    return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
  }

  @Override
  public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames,
      Type[] types) {
    if (entity instanceof Creatable) {
      Creatable log = (Creatable) entity;
      User user = userDao.getActiveUser();
      Date now = DateHelper.getCurrentDateTime();
      log.setCreatedBy(user);
      log.setCreatedDate(now);
      for (int i = 0; i < propertyNames.length; i++) {
        if (ObjectUtils.nullSafeEquals("createdBy", propertyNames[i])) {
          state[i] = user;
        } else if (ObjectUtils.nullSafeEquals("createdDate", propertyNames[i])) {
          state[i] = now;
        }
      }
      return true;
    }
    return super.onSave(entity, id, state, propertyNames, types);
  }
}
